package com.sxjh.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 跨域配置
 * 
 * @author zixin
 */
@Configuration
public class ResourcesConfig implements WebMvcConfigurer {

    @Autowired
    private AuthFilter authFilter;

    private CorsConfiguration buildConfig() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedHeader("*"); // 1允许任何域名使用
        config.addAllowedOriginPattern("*"); // 2允许任何头
        config.addAllowedMethod("*"); //3允许任何方法（post、get等）
        config.setAllowCredentials(true); // 允许跨域带上cookies
        config.setMaxAge(18000L); // 4预检请求的缓存时间（秒），即在这个时间段里，对于相同的跨域请求不会再预检了
        return config;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 权限拦截器
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        WebMvcConfigurer.super.addInterceptors(registry);
        registry.addInterceptor(authFilter).addPathPatterns("/**");
    }
}